"""
应用管理 API 路由
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from database import get_db
from models.config_presets import Application
from schemas.config_preset_schema import (
    ApplicationCreate,
    ApplicationUpdate,
    ApplicationResponse,
    ApplicationListResponse,
)

router = APIRouter(prefix="/api/applications", tags=["应用管理"])


@router.post("", response_model=ApplicationResponse, summary="创建应用")
def create_application(
    application_create: ApplicationCreate,
    db: Session = Depends(get_db)
):
    """创建应用"""
    # 检查名称是否重复
    existing = db.query(Application).filter(Application.name == application_create.name).first()
    if existing:
        raise HTTPException(status_code=400, detail=f"应用名称 '{application_create.name}' 已存在")

    application = Application(
        name=application_create.name,
        description=application_create.description,
        appid=application_create.appid,
        hw_id=application_create.hw_id,
        hw_appkey=application_create.hw_appkey,
        vender=application_create.vender,
        region=application_create.region,
        trainApiVersion=application_create.trainApiVersion,
        created_by=application_create.created_by,
    )
    db.add(application)
    db.commit()
    db.refresh(application)
    return application


@router.get("", response_model=ApplicationListResponse, summary="获取应用列表")
def get_applications(
    active_only: bool = True,
    db: Session = Depends(get_db)
):
    """获取应用列表"""
    query = db.query(Application)
    if active_only:
        query = query.filter(Application.is_active == True)

    applications = query.order_by(Application.created_at.desc()).all()
    return ApplicationListResponse(
        total=len(applications),
        items=applications
    )


@router.get("/{application_id}", response_model=ApplicationResponse, summary="获取应用详情")
def get_application(
    application_id: int,
    db: Session = Depends(get_db)
):
    """获取应用详情"""
    application = db.query(Application).filter(Application.id == application_id).first()
    if not application:
        raise HTTPException(status_code=404, detail="应用不存在")
    return application


@router.put("/{application_id}", response_model=ApplicationResponse, summary="更新应用")
def update_application(
    application_id: int,
    application_update: ApplicationUpdate,
    db: Session = Depends(get_db)
):
    """更新应用"""
    application = db.query(Application).filter(Application.id == application_id).first()
    if not application:
        raise HTTPException(status_code=404, detail="应用不存在")

    # 检查名称是否重复（排除自己）
    if application_update.name and application_update.name != application.name:
        existing = db.query(Application).filter(
            Application.name == application_update.name,
            Application.id != application_id
        ).first()
        if existing:
            raise HTTPException(status_code=400, detail=f"应用名称 '{application_update.name}' 已存在")

    # 更新字段
    if application_update.name is not None:
        application.name = application_update.name
    if application_update.description is not None:
        application.description = application_update.description
    if application_update.appid is not None:
        application.appid = application_update.appid
    if application_update.hw_id is not None:
        application.hw_id = application_update.hw_id
    if application_update.hw_appkey is not None:
        application.hw_appkey = application_update.hw_appkey
    if application_update.vender is not None:
        application.vender = application_update.vender
    if application_update.region is not None:
        application.region = application_update.region
    if application_update.trainApiVersion is not None:
        application.trainApiVersion = application_update.trainApiVersion
    if application_update.is_active is not None:
        application.is_active = application_update.is_active

    db.commit()
    db.refresh(application)
    return application


@router.delete("/{application_id}", summary="删除应用")
def delete_application(
    application_id: int,
    db: Session = Depends(get_db)
):
    """删除应用"""
    application = db.query(Application).filter(Application.id == application_id).first()
    if not application:
        raise HTTPException(status_code=404, detail="应用不存在")

    # 检查是否有关联的配置预设
    if application.obs_bucket_presets or application.resource_pool_presets or application.image_presets:
        raise HTTPException(status_code=400, detail="该应用下存在配置预设，无法删除")

    db.delete(application)
    db.commit()
    return {"message": "应用已删除"}
